package com.caszx.chargingpile.fragment.user;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.fragment.BaseNetViewFragment;
import com.app.jsonparse.JSONParse;
import com.app.utils.DividerGridItemDecoration;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.entity.EntityStoreupOrders;
import com.caszx.chargingpile.holder.user.OrderReservateHolder;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**
 * 订单记录->预约订单
 */
public class UserOrderReservateFragment extends BaseNetViewFragment {


    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<EntityStoreupOrders> mRecyclerAdapter;
    private List<EntityStoreupOrders> mItems;
    private double storeupFees;
    private TextView txt_total_fee;

    private DecimalFormat decimalFormat = new DecimalFormat("￥###.##");
    public static UserOrderReservateFragment newInstance(double storeupFees,String storeupOrders ) {
        UserOrderReservateFragment fragment = new UserOrderReservateFragment();
        Bundle bundle = new Bundle();
        bundle.putDouble("storeupFees",storeupFees);
        bundle.putString("storeupOrders",storeupOrders);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            storeupFees = getArguments().getDouble("storeupFees");
            String storeupOrders =  getArguments().getString("storeupOrders");
            mItems = JSONParse.parseArray(storeupOrders,EntityStoreupOrders.class);

        }
    }

    @Override
    protected void onLoad() {
        showContentView();
    }

    @Override
    protected View initOnloadedView() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.fragment_user_order_record, null);
        initRecyclerView(view);

        txt_total_fee = (TextView) view.findViewById(R.id.txt_total_fee);
        txt_total_fee.setText("预约消费总额 " +decimalFormat.format(storeupFees));
        return  view;
    }

    private void initRecyclerView(View view) {

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setBackgroundResource(R.color.white);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        LinearLayoutManager layoutManager = new LinearLayoutManager( getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(getContext()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_user_order_reservate,OrderReservateHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);
        mRecyclerAdapter.setDatas(mItems);
        mRecyclerAdapter.setOnItemClickListener(new BaseClickRecyclerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getordersDetail(mRecyclerAdapter.getItems().get(position).ordersId);
            }
        });
    }

    private void getordersDetail(String ordersId){

        showProgressDialog("获取订单详情");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_ORDERS_DETAIL_)
                .addParams("ordersId",ordersId)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        SnackbarHelp.showSnackbarMsg(getActivity(),getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                SnackbarHelp.showSnackbarMsg(getActivity(), resultJsonObject.optString("msg"));
                            } else {
                                try {

                                    StringBuilder builder = new StringBuilder();
                                    builder.append("桩号:").append(response.optString("pileNo")).append("\n");
                                    builder.append("枪号:").append(response.optString("gunNo")).append("\n");
                                    builder.append("电站名称:").append(response.optString("stationName")).append("\n");
//                                    builder.append("订单号:").append(response.optString("ordersId")).append("\n");
                                    builder.append("开始时间:").append(response.optString("sTime")).append("\n");
                                    builder.append("结束时间:").append(response.optString("eTime")).append("\n");
                                    builder.append("用电量:").append(response.optString("chargePower")).append("\n");
                                    builder.append("充电费用:").append(response.optString("chargeFees")).append("\n");
                                    builder.append("总费用:").append(response.optString("totalFees")).append("\n");
                                    builder.append("时长（分）:").append(response.optString("timeLong")).append("\n");

                                    SimpleDialog.Builder builderDialog = new SimpleDialog.Builder(R.style.SimpleDialogLight);
                                    builderDialog.title("订单详情");
                                    builderDialog.message(builder.toString());
                                    builderDialog.positiveAction("确定");
                                    DialogFragment fragment = DialogFragment.newInstance(builderDialog);
                                    fragment.show(getChildFragmentManager(), null);
                                } catch (JSONException e) {
                                    SnackbarHelp.showSnackbarMsg(getActivity(), getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }
}
